import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:riverpod_t/page/car/data/model/info_model.dart';
import 'package:riverpod_t/page/car/event/car_info_op_event.dart';
import 'package:riverpod_t/page/car/state/car_op_state.dart';
part 'car_info_op_river.g.dart';

@riverpod
class CarInfoOpRiver extends _$CarInfoOpRiver {
  @override
  Future<CarInfoOpState> build() async {
    return CarInfoOpState(op: const CarInfoNoneOp());
  }

  /// 无事件操作
  void _setNoneOp() {
    state = AsyncValue.data(CarInfoOpState(op: const CarInfoNoneOp()));
  }

  /// 喜欢 || 取消喜欢
  void addLike(CarInfoLikeOp op) async {
    state = const AsyncValue.loading();
    try {
      bool success = await _like(op.model);
      state = AsyncValue.data(CarInfoOpState(op: op, isSuccess: success, model: op.model));
      _setNoneOp();
    } catch (err, stack) {
      state = AsyncValue.error(err, stack);
    }
  }

  /// 删除
  Future<void> removeCarInfo(CarInfoRemoveOp op) async {
    state = const AsyncValue.loading();
    try {
      bool success = await _remove(op.model);
      state = AsyncValue.data(CarInfoOpState(op: op, isSuccess: success, model: op.model));
      _setNoneOp();
    } catch (err, stack) {
      state = AsyncValue.error(err, stack);
    }
  }

  /// 删除数据请求
  Future<bool> _remove(InfoModel model) async {
    /// 模拟请求删除接口
    await Future.delayed(const Duration(seconds: 2), () {});
    return true;
  }

  Future<bool> _like(InfoModel model) async {
    /// 1:喜欢 2:取消喜欢
    return true;
  }
}
